import { menuModel, starModel } from "./../model/menuModel";
import * as moment from "moment";
import * as rq from 'request-promise';
import env from "./../config/env";
const xlsx = require('node-xlsx');
import * as fs from 'fs'

export class menuService {

    //新增 工会
    async createMenu(res: any) {
        menuModel.create(res).then();
        return { code: 100 };
    }

    async queryList() {
        let result = await menuModel.find().sort({ sort: 1 });
        return { code: 100, data: result }
    }

    /**
     * 
     * 1、根据userId 查询是否存在评分
     * 2、如果存在判断失效时间 是否已经超过 
     * 3、如果未超过 则返回 code 101 今天您已经评论过了，明天再来
     * 4、如果超过 则根据 userId 修改 starModel
     * 
     * @param res 
     */
    async updateMenuById(res) {
        console.log('res__________________', res);
        let star: string = res.star;
        let menuId: string = res._id;
        let openId: string = res.openId;

        let day_: string = moment().add('days', 7).format("YYYY-MM-DD");
        //1
        let find_user: any = await starModel.findOne({ openId: openId, menuId: menuId });
        if (find_user) {
            //2
            let invalid: string = find_user.invalid;
            if (day_ <= invalid) return { code: 101, msg: '今天您已经评论过了，明天再来~' };
        }
        //3
        await starModel.update({ openId: openId, menuId: menuId }, {
            menuId: menuId,
            openId: openId,
            star: star,
            invalid: day_
        }, { upsert: true });

        //查询并计算平均值
        let find_star: any = await starModel.aggregate([
            {
                $match: {
                    menuId: menuId
                }
            },
            {
                $group: {
                    _id: null,
                    val: { $avg: '$star' }
                }
            }
        ])
        console.log(find_star, 'find_star平均值================>')
        console.log('parseInt(find_star[0].val)__________________', Math.ceil(find_star[0].val));

        await menuModel.update({ _id: menuId }, { star: Math.ceil(find_star[0].val) }, { upsert: false })

        return { code: 100 };
    }


    /**
     * 获取openId
     * @param res 
     */
    async queryOpenIdByCode(res: any) {
        console.log('用户code__________________', res);
        let json = await rq.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${env.menu_appid}&secret=${env.menu_secret}&js_code=${res.code}&grant_type=authorization_code`,
            {
                json: true
            })
        console.log('获取用户openId__________________', json);
        return json;
    }

    // 测试专用  这个接口无实际意义 
    async testUpdate() {
        console.log('进入测试接口__________________', );
        let findList: any = await menuModel.find();
        console.log('findList__________________', findList.length);
        for (var i = 0; i < findList.length; i++) {
            var element = findList[i];
            console.log('__________________', element.name.substr(0, 2));
            switch (element.name.substr(0, 2)) {
                case '大厅':
                    await this.upd(element._id, 1);
                    break;
                case 'FL':
                    await this.upd(element._id, 2);
                    break;
                case '筷乐':
                    await this.upd(element._id, 3);
                    break;
                case '风味':
                    await this.upd(element._id, 4);
                    break;
            }
        }
    }
    /**
     * 导出excel
     *  菜品名称，评分，被点次数
     * 
     */
    async excel() {
        let dishes = await menuModel.find({})

        let cache = {}
        let excel: any = []
        excel.push(['菜品名称', '平均评分', '被点次数'])

        dishes.map(item => {
            cache[item._id] = item
        })
        for (var key in cache) {

            if (cache.hasOwnProperty(key)) {
                let item = cache[key];
                let menuId = item._id
                let name = item.name
                let star = item.star
                let count = await starModel.count({ menuId: menuId })
                excel.push([name, star, count])
            }
        }
        let buffer = xlsx.build([{ name: `菜品详情表`, data: excel }]);
        fs.writeFileSync('./菜品详情表.xlsx', buffer);
    }

    async upd(_id: string, num: number) {
        let result = await menuModel.update({ _id: _id }, { sort: num }, { upsert: false });
        console.log('result__________________', result);
    }

}

export default new menuService();